package com.jt.service;

import com.jt.vo.ImageVo;
import com.jt.vo.SysResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author 刘昱江
 * 时间 2021/4/14
 */
@Service
@PropertySource("classpath:/properties/image.properties")
public class FileServiceImpl implements FileService {

    @Value("${image.localDirPath}")
    private String localDirPath;
    @Value("${image.urlPath}")
    private String urlPath;

    @Override
    public SysResult upload(MultipartFile file) {
        //1.获取商品名称  1.jpg
        String fileName = file.getOriginalFilename();
        fileName = fileName.toLowerCase();
        //2.判断图片类型是否有效
        if(!fileName.matches("^.+\\.(jpg|png|gif)$")){

            return SysResult.fail("图片类型不匹配");
        }

        //3.准备文件上传目录
        //3.1 准备时间文件目录
        String datePath = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
        String fileDirPath = localDirPath + datePath;
        File dirFile = new File(fileDirPath);
        //如果不存在,则创建目录
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }

        //4.防止文件重名生成UUID名称
        String uuid = UUID.randomUUID().toString().replace("-", "");
        //4.1获取图片类型
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        //4.2生成图片名称
        String uuidName = uuid + fileType;

        //5.实现文件上传
        String realFilePath = fileDirPath + uuidName;
        File picFile = new File(realFilePath);
        try {
            file.transferTo(picFile);
        } catch (IOException e) {
            e.printStackTrace();
            return SysResult.fail("文件上传失败");
        }

        //准备图片虚拟路径
        String picUrlPath = urlPath + datePath + uuidName;
        String virtualPath = datePath+uuidName;
        ImageVo imageVo = new ImageVo(virtualPath, picUrlPath,uuidName);
        return SysResult.success(imageVo);
    }

    @Override
    public void deleteFile(String virtualPath) {
        //拼接磁盘路径
        String localPath = localDirPath + virtualPath;
        File file = new File(localPath);
        file.delete();
    }
}
